package com.zjl.spring.第07章_资源操作Resources;

import com.zjl.spring.第06章_事务.全注解事务配置;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

/**
 * ResourceLoaderAware接口实现类的实例将获得一个ResourceLoader的引用，
 * ResourceLoaderAware接口也提供了一个setResourceLoader()方法，
 * 该方法将由Spring容器负责调用，Spring容器会将一个ResourceLoader对象作为该方法的参数传入。
 *
 * 如果把实现ResourceLoaderAware接口的Bean类部署在Spring容器中，
 * Spring容器会将自身当成ResourceLoader作为setResourceLoader()方法的参数传入。
 * 由于ApplicationContext的实现类都实现了ResourceLoader接口，Spring容器自身完全可作为ResourceLoader使用。
 */
@Configuration//配置类
@ComponentScan(basePackages = "com.zjl.spring.第07章_资源操作Resources")//组件扫描
public class C_ResourceLoaderAware {
    public static void main(String[] args) {
//        ApplicationContext context = new ClassPathXmlApplicationContext();
        ApplicationContext context = new AnnotationConfigApplicationContext(C_ResourceLoaderAware.class);

        //用于 如 SpringBoot 获取 Resource 和 ApplicationContext 等
        TestBean testBean = context.getBean("testBean", TestBean.class);
        ResourceLoader resourceLoader = testBean.getResourceLoader();
        ApplicationContext applicationContext = testBean.getApplicationContext();

        System.out.println(applicationContext == context);//true

        //因为 ApplicationContext 继承了 ResourcePatternResolver  又继承了 ResourceLoader  都是同一个
        System.out.println(context == resourceLoader);//true
    }
}
@Service
class TestBean implements ResourceLoaderAware, ApplicationContextAware {

    private ResourceLoader resourceLoader;
    private ApplicationContext applicationContext;
    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public ResourceLoader getResourceLoader(){
        return resourceLoader;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    public ApplicationContext getApplicationContext(){
        return applicationContext;
    }
}